using System;
using System.Collections.Generic;
using System.Linq;
using ReagentStore.ERM;

namespace ReagentStore.DAL
{
	public class RecordDAL : IDALBase<Record>
	{
		#region Implementation of IDALBase<T>

		public IList<Record> GetEntities()
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
				return db.Records.ToList();
		}

		public Record GetEntityById(int id)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
				return db.Records.SingleOrDefault(s => id.Equals(s.RecordID));
		}

		public void Insert(Record record)
		{
			if (record == null)
				return;

			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
			{
				db.Records.AddObject(record);
				db.SaveChanges();
			}
		}


		public void Update(Record record)
		{
			throw new NotImplementedException();
		}

		public void Delete(Record record)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
			{
				Record exist = GetEntityById(record.RecordID);
				db.Records.Attach(exist);
				db.Records.DeleteObject(exist);
				db.SaveChanges();
			}
		}

		#endregion

		public IList<Record> GetEntitiesByProductId(int productId)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
				return db.Records.Where(w => productId.Equals(w.ProductID)).ToList();
		}

		public IList<Record> GetEntitiesByReagentId(int reagentId)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
			{
				var list = new List<Record>();
				IList<Product> products = new ProductDAL().GetEntitiesByReagentId(reagentId);

				foreach (Product product in products)
					list.AddRange(GetEntitiesByProductId(product.ProductID));

				return list;
			}
		}
	}
}